package org.ascollada.io
{
	import flash.errors.IOError;
	import flash.net.URLRequest;
	
	import org.libspark.thread.Thread;
	import org.libspark.thread.threads.net.URLLoaderThread;

	public class DaeXrefLoaderThread extends Thread
	{
		private var _urls :Array;
		private var _loader :URLLoaderThread;
			
		/**
		 * 
		 */ 
		public function DaeXrefLoaderThread()
		{
			super();
			
			_urls = new Array();
		}
		
		/**
		 * 
		 */ 
		public function addFile(url:String):void
		{
			_urls.push(url);
		}
		
		/**
		 * 
		 */ 
		protected override function run():void
		{
			if(!_urls || !_urls.length)
			{
				return;
			}
			
			_loader = new URLLoaderThread(new URLRequest(String(_urls.shift())));
			_loader.start();
			_loader.join();
			
			next(executeComplete);

			error(IOError, errorHandler);
			error(SecurityError, errorHandler);
		}
		
		/**
		 * 
		 */ 
		private function executeComplete():void
		{
			//debug
			trace("MainThread Complete Loading. " + _urls.length );
			
			if(_urls.length)
			{
				run();
			}
		}
		
		/**
		 * 
		 */ 
		private function errorHandler(e:IOError, t:Thread):void
		{
			//debug
			trace("MainThread Error.");

			//例外を出力して終了
			trace(e.getStackTrace());

			//例外ハンドラから終了する
			if(_urls.length)
			{
				run();
			}
			else
			{
				next(null);
			}
		}
	}
}